package com.example.consulconsumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@RestController
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("consumer-test")
    public String test() {
        //String rst = "";

        //通过consumer去访问provier
        //String rst = restTemplate.getForObject("http://provider/pro-test" , String.class );


        List<ServiceInstance> instances = this.discoveryClient.getInstances("provider");
        ServiceInstance serviceInstance = instances.get(0);
        URI uri = serviceInstance.getUri();
        String targetUrl = uri + "/pro-test";

        String rst = restTemplate.getForObject(targetUrl, String.class);

        return "consumer : " + rst;
    }


}
